package com.neusoft.bizcore.auth.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.auth.dto.AuthOganizationDTO;
import com.neusoft.bizcore.auth.model.AuthOganization;
import com.neusoft.bizcore.auth.repository.AuthOganizationRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.bizcore.web.exception.UnitedException;

@Component
public class AuthOganizationConverter extends AbstractConverter<AuthOganization, AuthOganizationDTO> {

    @Autowired
    private AuthOganizationRepository authOganizationRepository;
    @Autowired
    private AuthUserConverter authUserConverter;

    @Override
    public AuthOganization toModel(final AuthOganizationDTO dto) {
        AuthOganization model;
        if (dto.isNew()) {
            model = new AuthOganization();
        } else {
            model = this.authOganizationRepository.getOne(dto.getId());
        }
        model.setName(dto.getName());
        model.setCode(dto.getCode());

        final AuthOganization parent = this.authOganizationRepository.findByCode(dto.getParent());
        if (null == parent) {
            throw new UnitedException("请选择上级组织");
        }
        model.setParent(parent);
        return model;
    }

    @Override
    public AuthOganizationDTO toDTO(final AuthOganization model, final boolean forListView) {
        final AuthOganizationDTO dto = new AuthOganizationDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        if (null != model.getParent()) {
            dto.setParent(model.getParent().getCode());
        }
        if (!forListView) {
            dto.getUsers().addAll(this.authUserConverter.toListDTO(model.getUsers()));
        }
        return dto;
    }

}
